"""
文件管理器 - 支持图片和描述文件分离存储
"""

import os
import time
from pathlib import Path
from typing import Optional


class FileManager:
    """文件管理器，支持图片和描述文件分离存储"""
    
    def __init__(self, config: dict = None):
        """
        初始化文件管理器
        
        Args:
            config: 配置字典
        """
        self.config = config or {}
        
        # 存储配置
        self.separate_files = self.config.get('separate_files', False)
        self.text_output_dir = self.config.get('text_output_dir', 'descriptions')
        self.description_format = self.config.get('description_format', 'txt')
        self.overwrite_existing = self.config.get('overwrite_existing', False)
        
        # 支持的图片格式
        self.supported_formats = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
        
        # 统计信息
        self.stats = {
            'images_processed': 0,
            'texts_created': 0,
            'errors': 0
        }
    
    def save_description(self, image_path: str, description: str) -> str:
        """
        保存描述文件
        
        Args:
            image_path: 图片文件路径
            description: 描述内容
            
        Returns:
            描述文件路径
        """
        try:
            image_path = Path(image_path)
            
            # 确定描述文件路径
            if self.separate_files:
                # 分离存储模式
                output_dir = Path(self.text_output_dir)
                output_dir.mkdir(parents=True, exist_ok=True)
                
                # 使用图片文件名（不含扩展名）
                base_name = image_path.stem
                text_path = output_dir / f"{base_name}.{self.description_format}"
            else:
                # 同目录存储模式
                text_path = image_path.with_suffix(f'.{self.description_format}')
            
            # 检查文件是否已存在
            if text_path.exists() and not self.overwrite_existing:
                raise FileExistsError(f"描述文件已存在: {text_path}")
            
            # 保存描述
            with open(text_path, 'w', encoding='utf-8') as f:
                f.write(description)
            
            self.stats['texts_created'] += 1
            return str(text_path)
            
        except Exception as e:
            self.stats['errors'] += 1
            raise e
    
    def description_exists(self, image_path: str) -> bool:
        """
        检查描述文件是否已存在
        
        Args:
            image_path: 图片文件路径
            
        Returns:
            描述文件是否存在
        """
        image_path = Path(image_path)
        
        if self.separate_files:
            output_dir = Path(self.text_output_dir)
            base_name = image_path.stem
            text_path = output_dir / f"{base_name}.{self.description_format}"
        else:
            text_path = image_path.with_suffix(f'.{self.description_format}')
        
        return text_path.exists()
    
    def get_description_path(self, image_path: str) -> str:
        """
        获取图片对应的描述文件路径
        
        Args:
            image_path: 图片文件路径
            
        Returns:
            描述文件路径
        """
        image_path = Path(image_path)
        
        if self.separate_files:
            output_dir = Path(self.text_output_dir)
            base_name = image_path.stem
            text_path = output_dir / f"{base_name}.{self.description_format}"
        else:
            text_path = image_path.with_suffix(f'.{self.description_format}')
        
        return str(text_path)
    
    def get_statistics(self) -> dict:
        """
        获取统计信息
        
        Returns:
            统计信息字典
        """
        return self.stats.copy()
    
    def reset_statistics(self) -> None:
        """重置统计信息"""
        self.stats = {
            'images_processed': 0,
            'texts_created': 0,
            'errors': 0
        }
    
    def validate_setup(self) -> tuple[bool, list[str]]:
        """
        验证设置
        
        Returns:
            (是否有效, 错误列表)
        """
        errors = []
        
        # 检查输出目录权限
        if self.separate_files:
            try:
                output_dir = Path(self.text_output_dir)
                output_dir.mkdir(parents=True, exist_ok=True)
                
                # 测试写入权限
                test_file = output_dir / ".test_write"
                test_file.touch()
                test_file.unlink()
            except Exception as e:
                errors.append(f"输出目录无写入权限: {e}")
        
        return len(errors) == 0, errors